package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CodeEnum;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.mapper.DishFlavorMapper;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl implements DishService {
    @Autowired
    DishMapper dishMapper;
    @Autowired
    DishFlavorMapper dishFlavorMapper;
    @Autowired
    CategoryMapper categoryMapper;

    /**
     * 查询是否有一个分类被菜品所关联
     *
     * @param id 分类的唯一标识
     * @return 当根据id查询到有数据关联返回false
     **/
    @Override
    public boolean hasCateId(Long id) {
        QueryWrapper<Dish> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category_id", id);
        if (dishMapper.selectList(queryWrapper).size() == 0) {
            return false;
        }
        return true;
    }

    @Override
    public void savDish(HttpServletRequest request, DishAndFlavor dishAndFlavor) {
        Dish dish = new Dish();
        List<DishFlavor> flavor = dishAndFlavor.getFlavors();
        BeanUtils.copyProperties(dishAndFlavor, dish);
        dish.setImage((String) request.getSession().getAttribute("image"));
        dishMapper.insert(dish);
        for (DishFlavor dishFlav : flavor) {
            dishFlav.setDishId(dish.getId());
            dishFlavorMapper.insert(dishFlav);
        }


    }

    @Override
    public R pageCategory(int page, int pageSize, String name) {
        //构造分页构造器
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        Page<DishDto> pageInfoNew = new Page<>(page, pageSize);
        //构造条件构造器
        QueryWrapper<Dish> queryWrapper = new QueryWrapper<>();
        if (name != null) {
            queryWrapper.like("name", name);
        }
        queryWrapper.orderByDesc("update_time");
        dishMapper.selectPage(pageInfo, queryWrapper);
        BeanUtils.copyProperties(pageInfo, pageInfoNew, "records");
        List<Dish> records = pageInfo.getRecords();
        List<DishDto> list = records.stream().map((item) -> {
            DishDto dto = new DishDto();
            BeanUtils.copyProperties(item, dto);
            Long categoryId = item.getCategoryId();
            Category category = categoryMapper.selectById(categoryId);
            String name1 = category.getName();
            dto.setCategoryName(name1);
            return dto;
        }).collect(Collectors.toList());
        //排序条件
        // 执行查询
        pageInfoNew.setRecords(list);
        return R.success(pageInfoNew);
    }

    @Override
    public DishAndFlavor getDishById(Long id) {
        DishAndFlavor flavor = new DishAndFlavor();
        Dish dish = dishMapper.selectById(id);
        BeanUtils.copyProperties(dish, flavor);
        QueryWrapper<DishFlavor> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dish_id", dish.getId());
        flavor.setFlavors(dishFlavorMapper.selectList(queryWrapper));
        return flavor;
    }

    @Override
    public void updateDish(HttpServletRequest request, DishAndFlavor dishAndFlavor) {
        Dish dish = new Dish();
        List<DishFlavor> flavor = dishAndFlavor.getFlavors();
        BeanUtils.copyProperties(dishAndFlavor, dish);
        dish.setImage(dishAndFlavor.getImage());
        dishMapper.updateById(dish);
        List<Long> list = new ArrayList<>();
        for (int i = 0; i < flavor.size(); i++) {
            list.add(flavor.get(i).getId());
        }
        QueryWrapper<DishFlavor> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dish_id", dish.getId());
        List<DishFlavor> dishFlavors = dishFlavorMapper.selectList(queryWrapper);
        for (int i = 0; i < dishFlavors.size(); i++) {
            if (!list.contains(dishFlavors.get(i).getId())) {
                dishFlavorMapper.deleteById(dishFlavors.get(i).getId());
            }
        }

        for (DishFlavor dishFlavor : flavor) {
            dishFlavor.setDishId(dish.getId());
            if (dishFlavor.getId() == null) {
                dishFlavorMapper.insert(dishFlavor);
            }
            dishFlavorMapper.updateById(dishFlavor);
        }

    }

    @Override
    public int selectDishByName(String name) {
        QueryWrapper<Dish> query = new QueryWrapper<Dish>();
        query.eq("name", name);
        Dish dish = dishMapper.selectOne(query);
        if (dish != null) {
            return CodeEnum.ERROR_HASENTITY;
        }
        return CodeEnum.SUCCESS;
    }

    @Override
    public void updateStatusById(Integer status, Long[] ids) {
        Dish dish = new Dish();
        dish.setStatus(status);
        for (int i = 0; i < ids.length; i++) {
            dish.setId(ids[i]);
            dishMapper.updateById(dish);
        }

    }

    @Override
    public void deleteDish(Long[] ids) {
        for (int i = 0; i < ids.length; i++) {
            dishMapper.deleteById(ids[i]);
        }

    }

    @Override
    public List<DishAndFlavor> selectListByCategoryId(Long categoryId) {
        QueryWrapper<Dish> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category_id", categoryId);
        List<Dish> dishes = dishMapper.selectList(queryWrapper);
        List<DishAndFlavor> dishAndFlavors = dishes.stream().map((item)->{
            DishAndFlavor dishAndFlavor = new DishAndFlavor();
            BeanUtils.copyProperties(item,dishAndFlavor);
            QueryWrapper dishWrapp = new QueryWrapper<>();
            dishWrapp.eq("dish_id" ,item.getId());
            List<DishFlavor> list = dishFlavorMapper.selectList(dishWrapp);
            dishWrapp.clear();
            dishAndFlavor.setFlavors(list);
            return dishAndFlavor;
        }).collect(Collectors.toList());
        return dishAndFlavors;
    }
}
